/** Copyright 2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.spring4facelets.security.ui;

import java.io.IOException;

import javax.faces.component.UIComponent;

import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;

import com.sun.facelets.FaceletContext;
import com.sun.facelets.tag.TagAttribute;
import com.sun.facelets.tag.TagConfig;
import com.sun.facelets.tag.TagHandler;

/**
 * Exposes the Authentication object to the body of the tag.
 *
 * @author Allen Parslow
 */
public class AuthenticationTagHandler extends TagHandler {

    private final TagAttribute var;

    /**
     * Create a new AuthorizeTagHandler instance, extracting
     * attribute-expressions from the specified TagConfig.
     *
     * @param config
     *            Configuration for the TagHandler.
     */
    public AuthenticationTagHandler(TagConfig config) {
        super(config);
        this.var = this.getRequiredAttribute("var");
    }

    /**
     * {@inheritDoc}
     */
    public void apply(FaceletContext ctx, UIComponent parent) throws IOException {

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();

        String varText = var.getValue(ctx);
        if (this.var != null) {
            ctx.setAttribute(varText, auth);
        }

        this.nextHandler.apply(ctx, parent);

    }
}
